package com.ns.school.common.utils;

import java.security.MessageDigest;
import java.util.Objects;

/**
 * 获取MD5
 */
public class Md5Util {

    private static final String ENCODING = "UTF-8";
    private static final String MD5 = "MD5";
    private static final String SALT = "a!8i$iH#5L%iP4]V8HX#$%&*!K";

    /**
     * 获取MD5-密码
     *
     * @param s
     * @return
     */
    public static String getMD5Pwd(String s) {
        return getMD5(getMD5(s) + SALT);
    }

    /**
     * 获取MD5
     *
     * @param s
     * @return
     */
    public static String getMD5(String s) {
        try {
            MessageDigest md = MessageDigest.getInstance(MD5);
            md.update(s.getBytes(ENCODING));
            byte[] b = md.digest();
            int i = 0;
            StringBuilder buf = new StringBuilder();
            for (byte value : b) {
                i = value;
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            return buf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取MD5方法(字母大写)
     *
     * @param s
     * @return
     */
    public static String getMD5Upper(String s) {
        return Objects.requireNonNull(getMD5(s)).toUpperCase();
    }

}
